/**
* AutoSWF - Cody Cushing. March 26, 2009
* Copyright (c) 2009 Cody Cushing
* No use restrictions. Maintain this notice in all versions. 
**/

package com.autoswf.core
{
	import flash.events.Event;
	
	/**
	 * Encapsulates an object reference that is being passed up a chain of command. Internal 
	 * methods to modify path information as it gets passed through nodes. 
	 */	
	public class Transport
	{
		protected static const DELIM:String = Delimiters.PATH_DELIMITER;
		protected var address:Array;		
		
		/**
		 * 
		 * @param message  An object or "->" delimited string of path ids. 
		 * @param path     A string of path ids if "message" is an object
		 */
		public function Transport(message:*, path:String = null)
		{
			/* message is a path e.g. "main" or "main->subsection" */
			if(message is String)
			{
				address = String(message).split(DELIM).reverse();
			}
			else  /* message is an object */
			{
				address = [message];
				
				if(path) /* only check path if there is an object being passed. */
				{
					var addPath:Array = path.split(DELIM).reverse();
					address = address.concat(addPath);
				}
			}
		}
		
		/**
		 * The top object id on the path stack. If there are no path ids, this will be the payload. 
		 */
		public function get proposition():*
		{
			return address[address.length - 1];
		}
		
		/**
		 * The bottom object on the path stack--payload of the transport object--typically an event.
		 */
		public function get message():*
		{
			return address[0];
		}
		
		internal function pushPath(node:IChainLink):void
		{
			address.push(node.id);
		}
		
		internal function popPath(node:IChainLink = null):void
		{
			address.pop();
		}
		
		/**
		 * Creates a path id from the objects in the path. If the last item is an event, its type is
		 * appended. 
		 */
		public function toString():String
		{
 			var length:int = address.length;
			var str:String = "";
			for(var i:int = length - 1; i > 0; i--) /* join paths with delimiter*/
			{
				str += address[i] + DELIM;
			}
			
			if(address[0] is Event) /* last param is event, add type to path id */
			{
				var type:String = Event(address[0]).type;
				return (str == "") ? type : str + Event(address[0]).type;
			}
			return (str == "") ? address[0] : str + address[0]; /* last param is string, add it */
		}
		
	}
}